package cn.itsource.inter;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.itsource.constants.Constants;
import cn.itsource.pojo.domain.Login;
import cn.itsource.pojo.domain.LoginRole;
import cn.itsource.pojo.domain.Role;
import cn.itsource.service.ILoginRoleService;
import cn.itsource.service.ILoginService;
import cn.itsource.service.IRoleService;
import cn.itsource.service.impl.LoginServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class AdminListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ILoginService loginService;

    @Autowired
    private ILoginRoleService loginRoleService;

    @Autowired
    private IRoleService roleService;

	@Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
//        ...初始化管理员,保存Login，密码使用 BCryptPasswordEncoder 加密...
        //查询数据库是否 初始化
        Login one = loginService.getOne(new LambdaQueryWrapper<Login>().eq(Login::getUsername, Constants.Login.ADMIN));
        if (one != null) {
            loginService.delById(one.getId());
        }

        Login login = new Login();
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        login.setId(snowflake.nextId());
        login.setUsername("admin");
        login.setPassword(passwordEncoder.encode("123456"));
        login.setType(Constants.Login.TYPE_ADMIN);
        login.setEnabled(true);
        loginService.save(login);

        //维护 role 和 permission中间表
        loginRoleService.save(new LoginRole(login.getId(),Constants.Login.LOGIN_ROLE,Constants.Login.LOGIN_ROLE));


    }
}